package cn.starrysky108.simpleerp.core.security;

import cn.starrysky108.simpleerp.core.base.BaseResponseEntity;
import cn.starrysky108.simpleerp.core.constant.RedisKeys;
import cn.starrysky108.simpleerp.core.util.HttpUtil;
import cn.starrysky108.simpleerp.core.util.JwtUtil;
import cn.starrysky108.simpleerp.core.util.RedisUtil;
import cn.starrysky108.simpleerp.pub.response.TokenResponse;
import cn.starrysky108.simpleerp.user.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Carl Lee
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final UserService userService;

    public LoginSuccessHandler(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        UserDetailsEntity user = (UserDetailsEntity) authentication.getPrincipal();
        //签发token
        TokenResponse tokenResponse = TokenResponse.builder()
                .refreshToken(JwtUtil.getRefreshToken(user.getUsername(), user.getId()))
                .accessToken(JwtUtil.getAccessToken(user.getUsername(), user.getId()))
                .user(userService.getUserVo(user.getId()))
                .build();
        //返回token到前端
        HttpUtil.customResponse(BaseResponseEntity.success(tokenResponse), response);
        //记录登录信息
        RedisUtil.sAdd(RedisKeys.ONLINE_USER + user.getId(), tokenResponse.getRefreshToken());

    }
}
